//===============================================================================
// Microsoft Architecture Strategy Team
// LitwareHR - SaaS Sample Application
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================


//===============================================================================
// Microsoft Architecture Strategy Team
// LitwareHR - S+S Sample Application
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================

using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;

using Microsoft.Practices.ObjectBuilder;
using Microsoft.Practices.CompositeUI;
using Microsoft.Practices.CompositeUI.EventBroker;

using LitwareHR.Infrastructure.Interface;
using LitwareHR.PublicApp.WinUX.Constants;
using LitwareHR.PublicApp.WinUX.Services;
using LitwareHR.Infrastructure.Interface.Constants;

using Shp.Runtime.Contract;
using System.Xml;
using System.IO;
using System.Windows.Data;

using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using LitwareHR.PublicApp.WinUX.Search;
using System.Windows.Media.Imaging;
using LitwareHR.PublicApp.WinUX.Entities;
using System.Globalization;

namespace LitwareHR.PublicApp.WinUX
{
    public partial class JobSearchViewPresenter : Presenter<IJobSearchView>
    {
        string filterColumnName;
        string filterColumnValue;
        RecruitingService _recruitingService = null;
        RolesIconService _rolesIconService = null;
        private PositionCollection openPositionList = new PositionCollection();
        private CubeFaceCollection cubeCollection = new CubeFaceCollection();
        private DataTable openPositionTable;
        private WindowsDesktopSearchResultsCollection wdsResults;
        private CollectionViewSource openPositions = new CollectionViewSource();

         public CubeFaceCollection CubeCollection
        {
            get
            {
                if (cubeCollection == null)
                    BuildCubeCollection();

                return cubeCollection;
            }
        }

        public CollectionViewSource OpenPositions
        {
            get
            {
                if (openPositions == null)
                    BuildOpenPositionList();
                return openPositions;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="recruitingService"></param>
        /// <param name="rolesIconService"></param>
        [InjectionConstructor]
        public JobSearchViewPresenter([ServiceDependency] RecruitingService recruitingService,
                                   [ServiceDependency] RolesIconService rolesIconService)
        {
            _recruitingService = recruitingService;
            _rolesIconService = rolesIconService;
            openPositions.Source = openPositionList;
            Initialize();
        }

        public override void OnViewReady()
        {
            base.OnViewReady();
            View.LoadResources();
            View.BindData();
            View.InitializeCube();
        }

        public void OnCloseView()
        {
            base.CloseView();
            WorkItem.SmartParts.Remove(View);
            if (View is IDisposable)
                ((IDisposable)View).Dispose();
        }


        private void Initialize()
        {
            GetJobDetailTable();
            wdsResults = new WindowsDesktopSearchResultsCollection();
        }

        internal void BindData()
        {
            RefreshData();
            View.ShowOpenPositions(openPositions);
            View.ShowCube(cubeCollection);
            View.ShowWdsResults(wdsResults);
        }

        internal void OnSelectedJob(string title)
        {
            View.DisplaySelectedJob(title, _rolesIconService.GetImage(title));
        }

        /// <summary>
        /// Return image path.
        /// </summary>
        /// <param name="roleName"></param>
        /// <returns></returns>
        public BitmapImage GetImage(string roleName)
        {
            return _rolesIconService.GetImage(roleName);
        }

        /// <summary>
        /// Get the data for Job Details.
        /// </summary>
        private void GetJobDetailTable()
        {
            openPositionTable = _recruitingService.GetOpenPositionsDetails();
        }

        /// <summary>
        /// 
        /// </summary>

        private void BuildCubeCollection()
        {
            if (openPositionTable == null)
                GetJobDetailTable();

            if (openPositionTable == null)
                return;

            Hashtable bag = GetOpenPositionByTitle(openPositionTable);
            int i = 0;
            CubeFace cubeTileList = null;

            //Check for any unfilled cube collections 
            if (cubeCollection.Count > 0 && cubeCollection[cubeCollection.Count - 1].Tiles.Count < 9)
            {
                cubeTileList = cubeCollection[cubeCollection.Count - 1];
                i = cubeCollection[cubeCollection.Count - 1].Tiles.Count;
            }
            else
            {
                cubeTileList = new CubeFace();
                cubeCollection.Add(cubeTileList);
            }

            //Delete: set count to 0 in current cube collection 
            foreach (CubeFace list in cubeCollection)
            {
                foreach (CubeTile tile in list.Tiles)
                {
                    if (!bag.Contains(tile.Title))
                        tile.Count = 0;
                }
            }

            if (bag.Count == 0)
                return;

            //Add / Update
            foreach (DictionaryEntry item in bag)
            {
                CubeTile cubeTile;

                //Check if Title already present
                cubeTile = GetCubeTile(item.Key.ToString());

                //If No, Add new 
                if (cubeTile == null)
                {
                    cubeTile = new CubeTile((int)item.Value,
                                                 item.Key.ToString(),
                                                 _rolesIconService.GetImage(item.Key.ToString()));
                    cubeTileList.AddTile(cubeTile);
                    i++;
                }
                else
                {
                    //Update Count
                    cubeTile.Count = (int)item.Value;
                }

                //Create new cube face after nine tiles 
                if (i == 9)
                {
                    i = 0;
                    cubeTileList = new CubeFace();
                    cubeCollection.Add(cubeTileList);
                }
            }

            if (cubeTileList.Tiles.Count == 0)
                cubeCollection.Remove(cubeTileList);
        }

        private CubeTile GetCubeTile(string title)
        {
            foreach (CubeFace cubeFace in cubeCollection)
            {
                foreach (CubeTile cubeTile in cubeFace.Tiles)
                {
                    if (cubeTile.Title == title)
                        return cubeTile;
                }
            }
            return null;
        }

        private static Hashtable GetOpenPositionByTitle(DataTable positionTable)
        {
            Hashtable bag = new Hashtable();
            string title = string.Empty;
            DataView positionTableView = new DataView(positionTable, "", "Title", DataViewRowState.CurrentRows);

            foreach (DataRowView row in positionTableView)
            {
                title = row["Title"].ToString();
                if (bag.ContainsKey(title))
                {
                    bag[title] = Int32.Parse(bag[title].ToString(), CultureInfo.InvariantCulture) + 1;
                }
                else
                {
                    bag.Add(title, 1);
                }
            }

            positionTableView.Dispose();
            return bag;
        }

        /// <summary>
        /// If Datatable (openPos) has all the OpenPositions
        /// Populate PositionCollection (openPositionList) using Datatable (openPos) 
        /// openPositionList will be filtered and used as DataSource for ListView        
        /// </summary>
        private void BuildOpenPositionList()
        {
            if (openPositionTable == null)
                GetJobDetailTable();

            if (openPositionTable == null)
                return;

            openPositionList.Clear();

            foreach (DataRow row in openPositionTable.Rows)
            {
                openPositionList.Add(new Position(row));
            }
        }

        public void DesktopSearch(string search)
        {
            DataTable wdsTable = WindowsDesktopSearch.ExecuteWindowsSearchQuery(search);
            wdsResults.Clear();
            if (wdsTable != null)
            {
                foreach (DataRow row in wdsTable.Rows)
                {
                    wdsResults.Add(new WindowsDesktopSearchResultItem(row));
                }
            }
        }

        /// <summary>
        /// Remove FilterEventHandler
        /// </summary>
        public void DetachOpenPositionsFilter()
        {
            OpenPositions.Filter -= new FilterEventHandler(OpenPositions_Filter);
        }

        /// <summary>
        /// Set the value of FieldName, FieldValue and then Add FilterEventHandler
        /// </summary>
        /// <param name="fieldName"></param>
        /// <param name="value"></param>
        public void FilterOpenPositions(string fieldName, string value)
        {
            filterColumnName = fieldName;
            filterColumnValue = value;
            OpenPositions.Filter += new FilterEventHandler(OpenPositions_Filter);
        }

        /// <summary>
        /// This method filters records depending on user selection
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpenPositions_Filter(object sender, FilterEventArgs e)
        {
            Position position = e.Item as Position;
            if (position != null)
            {
                if (filterColumnName.Length == 0)
                {
                    if (position.Code.Contains(filterColumnValue) || position.Title.Contains(filterColumnValue) || position.PostedOn.Contains(filterColumnValue))
                        e.Accepted = true;
                    else
                        e.Accepted = false;
                }
                else if (filterColumnName.Equals("title", StringComparison.InvariantCultureIgnoreCase))
                {
                    // User has clicked on Cube Tile
                    // So consider only title for searching
                    e.Accepted = (position.Title == filterColumnValue);
                }
                else
                {
                    // Just for safety
                    e.Accepted = false;
                }
            }
        }

        #region Meta Model Changed Events

        [EventSubscription(EventTopicNames.MetaModelUpdating, ThreadOption.UserInterface)]
        public void OnMetaModelUpdating(object sender, EventArgs eventArgs)
        {
            // Start
            View.StartSyncAnimation();
        }

        [EventSubscription(EventTopicNames.MetaModelUpdated, ThreadOption.UserInterface)]
        public void OnMetaModelUpdated(object sender, EventArgs eventArgs)
        {
            // End
            View.BindData();
            View.NotifySchemaChanges();
            View.EndSyncAnimation();
        }

        #endregion

        #region Data Synchronization Events

        [EventSubscription(EventTopicNames.DataSynchronizing, ThreadOption.UserInterface)]
        public void OnDataSynchronizing(object sender, EventArgs eventArgs)
        {
            // Start
            View.StartSyncAnimation();
        }

        [EventSubscription(EventTopicNames.DataSynchronized, ThreadOption.UserInterface)]
        public void OnDataSynchronized(object sender, EventArgs eventArgs)
        {
            View.BindData();
            View.EndSyncAnimation();
        }

        #endregion

        public void RefreshData()
        {
            GetJobDetailTable();
            BuildCubeCollection();
            BuildOpenPositionList();
        }
    }
}

